/*
 * (c) Copyright 2009 Hewlett-Packard Development Company, LP
 * All rights reserved.
 * [See end of file]
 */

package com.hp.hpl.jena.clusteredtdb.comms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import com.hp.hpl.jena.clusteredtdb.ClusteredTDBConfig;
import com.hp.hpl.jena.clusteredtdb.ServerConfigEntry;
import com.hp.hpl.jena.clusteredtdb.VNodeConfigEntry;

public class ClusterRepresentation {

    // Model of the system (move?)
	HashMap<Integer,RemoteServer> serverMap;
	HashMap<Integer,RemoteVNode> vnodeMap;
		
	public ClusterRepresentation(ClusteredTDBConfig ctdb) {

		this.vnodeMap = new HashMap<Integer,RemoteVNode>();
		this.serverMap = new HashMap<Integer,RemoteServer>();
		init(ctdb);
	}
	
	private void init(ClusteredTDBConfig ctdb) {
		ServerConfigEntry[] svs = ctdb.getServers();
		VNodeConfigEntry[] vns = ctdb.getVNodes();
		for(int i = 0; i < svs.length;i++) {
			this.serverMap.put(new Integer(svs[i].getServerId())
					,new RemoteServer(svs[i].getHostname(),svs[i].getPort()
							,svs[i].getServerId(),svs[i].getMaxConns()));
		}
		for(int i = 0; i < vns.length;i++) {
			RemoteVNode vn = new RemoteVNode(serverMap.get(new Integer(vns[i].getServerId()))
					,vns[i].getVnodeId());
			this.vnodeMap.put(new Integer(vns[i].getVnodeId()),vn);
			this.serverMap.get(new Integer(vns[i].getServerId())).addVNode(vn);
		}
	}
	
	/*
	 * Sends to all vnodes on every server, including mirrors
	 */
	public ResponseProcessor BroadcastAllRequest(ArrayList<String> request, ResponseProcessor rp) {
		Iterator<RemoteServer> it = serverMap.values().iterator();
		while(it.hasNext()) {
			RemoteServer rs = it.next();
			rs.queryServer(request, rp);
		}
		return rp;
	}
	
	public int getVNodeCount() {
		return vnodeMap.size();
	}
	
	public int getServerCount() {
		return serverMap.size();
	}
	
	/*
	 * Same as BroadcastAllRequest for now, but will change when vnode mirroring
	 * comes in to play
	 */
	public ResponseProcessor BroadcastAllVNodesRequest(ArrayList<String> request, ResponseProcessor rp) {
		Iterator<RemoteServer> it = serverMap.values().iterator();
		while(it.hasNext()) {
			RemoteServer rs = it.next();
			rs.queryServer(request, rp);
		}
		return rp;
	}
	
	/*
	 * Sends to a request's first vnode.  'mirroring' currently does nothing, but
	 * when vnode mirroring is implemented needs to send to all mirrors or not
	 * based on value.  (TODO: implement error checking)
	 */
	public ResponseProcessor SendOneVNode(Request req, ResponseProcessor rp) {
		RemoteVNode vn = vnodeMap.get(new Integer(req.getFirstVNode().getId()));
		return vn.sendSimpleRequest(req.getRequestText(), rp, req.getMirror());
	}
	
	/*
	 * Sends multiple requests, taking responsibility for all threading, etc.
	 * TODO multi thread. Implement for multiple vnodes, etc. 
	 * TODO handle interruptedexceptions gracefully
	 */
	public ResponseProcessor SendMultipleRequests(Iterator<Request> reqs, ResponseProcessor rp) {
		ArrayList<Thread> threads = new ArrayList<Thread>();
		while(reqs.hasNext()) {
			Request req = reqs.next();
			RemoteVNode vn = vnodeMap.get(new Integer(req.getFirstVNode().getId()));
			RequestThread rt = new RequestThread(this,req,rp);
			Thread t = new Thread(rt);
			threads.add(t);
			t.start();
			//vn.sendSimpleRequest(req.getRequestText(), rp, req.getMirror());
		}
		
		//wait for threads to complete.
		Iterator<Thread> it = threads.iterator();
		try {
			while(it.hasNext()) {
				Thread t = it.next();
				t.join();
			}
		} catch (InterruptedException e) {

		}
		
		return rp;
	}
	
	/*
	 * TODO: implement
	 * Sends to multiple vnodes.  boolean value 'mirror' currently does nothing, but
	 * when vnode mirroring is implemented needs to send to all mirrors or not
	 * based on value
	 */
	public ResponseProcessor SendMultipleVNode(ArrayList<Integer> vnodes, ArrayList<String> request, ResponseProcessor rp, boolean mirror) {
		return null;
	}
	
	
	
	/*
	 * Sends to all the vnodes on a given server.
	 */
	public ResponseProcessor SendOneServer(int server, ArrayList<String> request, ResponseProcessor rp) {
		RemoteServer rs = serverMap.get(new Integer(server));
		return rs.queryServer(request, rp);
	}
	
	public HashMap<Integer,RemoteVNode> getNodesForServer(int server) {
		RemoteServer rs = serverMap.get(new Integer(server));
		if(rs != null) {
			return rs.getVNodeMap();
		} else {
			return null;
		}
	}
	
	public RemoteVNode getVNodeForId(int id) {
		return vnodeMap.get(new Integer(id));
	}
	
	class RequestThread implements Runnable {
		ClusterRepresentation parent;
		Request req;
		ResponseProcessor rp;
		
		public RequestThread(ClusterRepresentation parent, Request req, ResponseProcessor rp) {
			this.parent = parent;
			this.req = req;
			this.rp = rp;
		}

		public void run() {
			//System.out.println("THREAD");
			parent.SendOneVNode(this.req, this.rp);
		}
		
		
	}
	
}

/*
 * (c) Copyright 2009 Hewlett-Packard Development Company, LP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
